package zj.com.activities;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tonicartos.widget.stickygridheaders.StickyGridHeadersGridView;
import com.tonicartos.widget.stickygridheaders.StickyGridHeadersSimpleArrayAdapter;

import org.xutils.db.Selector;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.db.table.DbModel;
import org.xutils.ex.DbException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import zj.com.adapter.ChoiceExpandableListViewAdapter;
import zj.com.adapter.ChoiceJcxAdapter;
import zj.com.app.ZjApplication;
import zj.com.db.DBUtil;
import zj.com.interfaze.Callback;
import zj.com.model.InspectContent;
import zj.com.model.InspectItem;
import zj.com.model.UserInfo;
import zj.com.model.Zy;
import zj.com.net.NetManager;
import zj.com.net.OnResponseListener;
import zj.com.util.DialogUtil;
import zj.com.util.LogUtils;
import zj.com.zj.R;

/**
 * Created by xi on 16/6/15.
 */
public class ChoiceJcxActivity extends BaseActivity implements View.OnClickListener,Callback{

    public TextView title_name,right_tv,cancel_tv,submit_tv,select_tv;
    public ImageView left_iv;
    public ListView asset_grid;
    public Intent intent;
    public final int ZY_CODE = 0x2210;
    public Zy zy;


    public List<InspectItem> list;
    public ChoiceJcxAdapter adapter;
    public RelativeLayout rl;

    public EditText search_et;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choice_jcx);
        initView();
    }

    public void initView(){

        rl = (RelativeLayout) findViewById(R.id.rl);
        select_tv = (TextView) findViewById(R.id.select_tv);
        cancel_tv = (TextView) findViewById(R.id.cancel_tv);
        cancel_tv.setOnClickListener(this);
        submit_tv = (TextView) findViewById(R.id.submit_tv);
        submit_tv.setOnClickListener(this);

        title_name = (TextView) findViewById(R.id.title_name);
        title_name.setText("选择检查项");
        right_tv = (TextView) findViewById(R.id.right_tv);
        right_tv.setVisibility(View.VISIBLE);
        right_tv.setText("工程专业");
        right_tv.setOnClickListener(this);
        left_iv = (ImageView) findViewById(R.id.left_iv);
        left_iv.setVisibility(View.VISIBLE);
        left_iv.setOnClickListener(this);

        asset_grid = (ListView) findViewById(R.id.asset_grid);
        list =new ArrayList<InspectItem>();
        adapter = new ChoiceJcxAdapter(this,list);
        adapter.setCallback(this);
        asset_grid.setAdapter(adapter);

        search_et= (EditText) findViewById(R.id.search_et);
        search_et.setVisibility(View.GONE);
        search_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                String keyword = s.toString();
                try{
                    if(!TextUtils.isEmpty(keyword) && zy != null){
                        List<InspectItem> items =  DBUtil.getInstance(ChoiceJcxActivity.this).getDBManager().selector(InspectItem.class).where("inspectttemname", "like", "%" + keyword + "%").and("specialtycode","=",zy.getSpecialtyCode()).findAll();
                        if(items != null && items.size() > 0){
                            list  = items;
                        }else{
                            list.clear();
                            //Toast.makeText(ChoiceJcxActivity.this,"没有你要搜索的数据",Toast.LENGTH_SHORT).show();
                        }
                        adapter.setDataChange(list);
                    }else{
                        initDataFromDB();
                    }
                }catch (Exception e)
                {

                }
            }
        });
       // setExp();

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {


        if(resultCode == RESULT_OK){

            switch (requestCode){

                case ZY_CODE:
                    zy = (Zy) data.getSerializableExtra("zy");
                    search_et.setVisibility(View.VISIBLE);
                    initValue();
                    break;
            }
        }

        super.onActivityResult(requestCode, resultCode, data);

    }

    public void initValue(){
        LogUtils.getInstance().error("code=" + zy.getSpecialtyCode());
        list.clear();
        adapter.setDataChange(list);
        try {
            List<InspectItem> list =  DBUtil.getInstance(this).getDBManager().selector(InspectItem.class).where("specialtycode","=",zy.getSpecialtyCode()).findAll();

            if(list != null && list.size() > 0){
                initDataFromDB();

            }else{
                obtainZyDetail();

                LogUtils.getInstance().error("=====obtainZyDetail=========");

            }



        } catch (DbException e) {
            rl.setVisibility(View.VISIBLE);
            e.printStackTrace();
        }
    }

    private void initDataFromDB(){
        try{


           List<DbModel> list = DBUtil.getInstance(this).getDBManager().selector(InspectItem.class)
                    .groupBy("risktype").select("riskname,risktype,specialtycode").where("specialtycode", "=", zy.getSpecialtyCode())
                   .findAll();

            LogUtils.getInstance().error("count ==="+list.size());
            List<InspectItem> inspectItems =new ArrayList<InspectItem>();
           for (int i=0;i<list.size();i++){

             InspectItem item = new InspectItem();
             DbModel model =  list.get(i);
             int risktype =  model.getInt("risktype");
             String riskname = model.getString("riskname");
               String specialtycode = model.getString("specialtycode");
               item.setRiskType(risktype);
               item.setRiskName(riskname);
               List<InspectItem>  items =  DBUtil.getInstance(this).getDBManager().selector(InspectItem.class).where("risktype","=",risktype).and("specialtycode","=",zy.getSpecialtyCode()).findAll();

               inspectItems.addAll(items);
           }

            rl.setVisibility(View.GONE);

            adapter.setDataChange(inspectItems);


        }catch(Exception e){

            LogUtils.getInstance().error(e.toString());
        }
    }



    public ProgressDialog dialog;

    public void obtainZyDetail(){



        if(zy == null) return;

        dialog = DialogUtil.createProgressDialog(this,"提示","数据获取中..");

        NetManager.getInstance(this).obtainInspectItemList(zy, new OnResponseListener<List<InspectItem>>() {
            @Override
            public void onComplete(boolean isOK, List<InspectItem> result, int errorCode, String errorMsg) {

                if(isOK){
                    initDataFromDB();

                }else{

                    Toast.makeText(ChoiceJcxActivity.this, "获取失败", Toast.LENGTH_SHORT).show();

                }
                dialog.dismiss();
            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {
                dialog.dismiss();
                Toast.makeText(ChoiceJcxActivity.this, "获取失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onClick(View v) {

        switch(v.getId()){
            case R.id.left_iv:
                finish();
                break;
            case R.id.right_tv:
                intent = new Intent(this,ZyActivity.class);
                startActivityForResult(intent,ZY_CODE);
                break;
            case R.id.cancel_tv:

                select_tv.setVisibility(View.GONE);
                adapter.notifyDataSetChanged();
                select_tv.setText("");

                break;
            case R.id.submit_tv:
                select();
                break;
        }
    }

    public void select(){

        Map<String,InspectItem> map =  adapter.getSelectMap();


        if(map != null){
            for(Map.Entry<String, InspectItem> entry:map.entrySet()){

                InspectItem item  = entry.getValue();

                boolean isExsit = false;
                for(int i=0;i<ZjApplication.inspectItems.size();i++){



                    InspectItem inspect =  ZjApplication.inspectItems.get(i);
                    LogUtils.getInstance().error("inspect====="+inspect.getInspectItemName()+","+inspect.getInspectItemCode()+",==="+item.getInspectItemName()+"  , "+item.getInspectItemCode());
                    if(inspect.getInspectItemCode().equals(item.getInspectItemCode())){
                        isExsit = true;
                    }

                }

                if(!isExsit){
                    ZjApplication.inspectItems.add(item);
                }
            }
        }
        finish();
    }

    public List<InspectItem> selectItems = new ArrayList<InspectItem>();
    @Override
    public void call() {
        select_tv.setVisibility(View.VISIBLE);

     StringBuffer sb =new StringBuffer();
     selectItems.clear();
     Map<String,InspectItem> map =  adapter.getSelectMap();
     if(map != null){
         sb.append("已选择:  ");
         for(Map.Entry<String, InspectItem> entry:map.entrySet()){

             InspectItem item  = entry.getValue();
             sb.append(item.getInspectItemName() + "   ");


         }
     }
       select_tv.setText(sb.toString());

    }
}
